//
// Created by armers on 2023/8/3.
//
#include "leclient.h"
#include <stdio.h>
#include <unistd.h>

static low_energy_status_e s_status = LE_STATUS_NORMAL;
static void handle_event(low_energy_event_e type)
{
    printf("event %d\n", type);
    s_status = LE_STATUS_TO_WAKE;
}

int main() {
    extern void detect_env_log_level();
    detect_env_log_level();
    low_energy_client_option_t opt = {
            .servers = "192.168.1.129:5683",
//            .servers = "192.168.1.127:5683",
            .product_code = "module38",
            .device_uid = "EPROS014JC1EJEQD1D012B51C0",
            .secret = "pkcr077sqix6r9iopytrq4x3totn8d6x",
            .event_cb = handle_event,
    };
    struct low_energy_client *client = create_le_client(&opt);
    s_status = LE_STATUS_SLEEPING;
    int ret = client->init(client);
    if(ret != 0) {
        printf("init failed: %d\n", ret);
        return ret;
    }
    ret = client->report(client, s_status);
    if(ret != 0) {
        printf("report failed: %d\n", ret);
    }
    while(1) {
//    for(int i=0; i< 10; i++) {
        //NOTE: not block handle_msg after report!!!
        ret = client->handle_msg(client, 2000);
        if(ret != 0) {
            printf("handle msg failed: %d\n", ret);
        }
        switch(s_status) {
            case LE_STATUS_SLEEPING: {
                break;
            }
            case LE_STATUS_TO_WAKE: {
                printf("report to wake\n");
                client->report(client, LE_STATUS_TO_WAKE);
                s_status = LE_STATUS_WAKING;
                break;
            }
            case LE_STATUS_WAKING: {
                printf("report waking, awake master\n");
                client->report(client, LE_STATUS_WAKING);
                s_status = LE_STATUS_WOKE;
                break;
            }
            case LE_STATUS_WOKE: {
                printf("woke\n");
                client->report(client, LE_STATUS_WOKE);
                s_status = LE_STATUS_NORMAL;
                break;
            }
            case LE_STATUS_NORMAL: {
                printf("change to sleeping again\n");
                client->report(client, LE_STATUS_SLEEPING);
                s_status = LE_STATUS_SLEEPING;
                break;
            }
        }
    }
    client->free(client);
    return 0;
}